import Vue from 'vue';
import { Module } from 'vuex';

interface SettingState {
  statusInfo: Record<string, number>; // 账户 key 对应的状态
}

const state: SettingState = {
  statusInfo: {}, // 初始化为空对象
};

const mutations = {
  /**
   * 设置账户状态
   * @param state
   * @param payload 包含账户 key 和状态
   */
  SET_STATUS_INFO(state: SettingState, payload: { key: string; status: number }) {
    Vue.set(state.statusInfo, payload.key, payload.status);
  },

  /**
   * 初始化所有账户状态为未创建
   * @param state
   * @param keys 账户 key 列表
   */
  INIT_STATUS_INFO(state: SettingState, keys: string[]) {
    keys.forEach((key) => {
      if (!(key in state.statusInfo)) {
        Vue.set(state.statusInfo, key, 0); // 0 表示未创建
      }
    });
  },
};

const actions = {
  /**
   * 更新账户状态
   * @param context
   * @param payload 包含账户 key 和状态
   */
  updateStatusInfo({ commit }, payload: { key: string; status: number }) {
    commit('SET_STATUS_INFO', payload);
  },

  /**
   * 初始化所有账户状态为未创建
   * @param context
   * @param keys 账户 key 列表
   */
  initializeStatusInfo({ commit }, keys: string[]) {
    commit('INIT_STATUS_INFO', keys);
  },
};

const getters = {
  /**
   * 获取特定账户的状态
   */
  getStatus:
    (state: SettingState) =>
      (key: string): number => 
        state.statusInfo[key] ?? 0 // 默认为未创建
  ,
};

const settingModule: Module<SettingState, any> = {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};

export default settingModule;
